package com.zyk.scaffold.gateway.components;

import com.zyk.scaffold.gateway.cache.Cache;
import com.zyk.scaffold.oauth.dto.AppInfoDTO;
import com.zyk.scaffold.oauth.dto.TokenInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 保存到缓存中
 */
@Slf4j
@Component
public class CacheComponent {
    public TokenInfoDTO getTokenInfoDTO(String accessToken, CallBack<TokenInfoDTO> defaultFunction) {
        return getValue(accessToken, Cache.USER_INFO, defaultFunction);
    }

    public AppInfoDTO getAppInfoDTO(String appId, CallBack<AppInfoDTO> defaultFunction) {
        return getValue(appId, Cache.APP_INFO, defaultFunction);
    }

    public <T> T getValue(String key, Cache cache, CallBack<T> defaultFunction) {
        Object value = cache.getCache(key, keyTmp -> defaultFunction.callBack(keyTmp));
        return (T) value;
    }

    @FunctionalInterface
    public interface CallBack<T> {
        /**
         * 回调
         **/
        T callBack(String key);
    }
}
